#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>

#define PORT 6666
using namespace std;

int main()
{
    int listen_fd, connect_fd;
    struct sockaddr_in server, client;
    socklen_t len;
    char buf[BUFSIZ];

    listen_fd = socket(AF_INET, SOCK_STREAM, 0); // 建立套接字
    bzero(&server, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(PORT);
    server.sin_addr.s_addr = htonl(INADDR_ANY);

    bind(listen_fd, (struct sockaddr *)&server, sizeof server); // 绑定 建立地址与套接字的关系

    listen(listen_fd, 5); // 监听 收消息 最大允许连接的数量
    len = sizeof client;
    connect_fd = accept(listen_fd, (struct sockaddr *)&client, &len);

    while (1)
    {

        bzero(&server, sizeof server);
        // connect_fd = accept(listen_fd, (struct sockaddr *)&client, &len);
        // 接受客户端的连接请求
        int n;
        n = read(connect_fd, buf, sizeof buf);
        puts(buf);

        write(connect_fd, buf, n);

        // close(connect_fd);
        //  bzero(&server, sizeof server);
        //  connect_fd = accept(listen_fd, (struct sockaddr *)&client, &len);
        //  // 接受客户端的连接请求
        //  int n;
        //  n = read(connect_fd, buf, sizeof buf);
        //  puts(buf);
        //  write(connect_fd, buf, n);
        //  close(connect_fd);
    }
    close(connect_fd);
    close(listen_fd);
    return 0;
}